package space.lichenpark.unfamiliar.components.influx.util;

import cn.hutool.core.util.StrUtil;
import com.influxdb.query.FluxColumn;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查询结果结果工具类
 *
 * @author Lichen
 */
public class ResultUtil {
/**
     * 将 FluxTable 列表按照 measurement + field 进行分类
     *
     * @param tables 查询结果表列表
     * @return 以 measurement+field 为键的分类结果集
     */
    public static Map<String, List<SimpleRecord>> simplify(List<FluxTable> tables) {
        Map<String, List<SimpleRecord>> groupedRecords = new HashMap<>();

        for (FluxTable table : tables) {
            // 获取表的列信息
            List<FluxColumn> columns = table.getColumns();

            // 查找 measurement 和 field 列
            String measurement = null;
            String field = null;

            for (FluxColumn column : columns) {
                if ("_measurement".equals(column.getLabel())) {
                    measurement = table.getRecords().get(0).getValueByKey("_measurement").toString();
                }
                if ("_field".equals(column.getLabel())) {
                    field = table.getRecords().get(0).getValueByKey("_field").toString();
                }
            }

            // 构造唯一键
            if (measurement != null && field != null) {
                String key = measurement + "+" + field;

                // 将 FluxRecord 简化为 SimpleRecord
                List<SimpleRecord> simpleRecords = new ArrayList<>();
                for (FluxRecord record : table.getRecords()) {

                    String time = null;
                    if (record.getTime() != null) {
                        time = StrUtil.sub(record.getTime().toString().replace("T", " "), 0, 19);
                    }

                    Object value = record.getValue();
                    simpleRecords.add(new SimpleRecord(time, value));
                }

                // 将记录添加到对应分类中
                groupedRecords.computeIfAbsent(key, k -> new ArrayList<>()).addAll(simpleRecords);
            }
        }

        return groupedRecords;
    }
}
